#include "head.h"
#define RED "\033[1;31m"
#define RESET "\033[0m"
// Print "REN MIN WAN SUI" in red color
void display() {
    const char *text_art[] = {
"    _   ______________   ____  _________ __ __ ",
"   / | / / ____/_  __/  / __ \\/  _/ ___// //_/ ",
"  /  |/ / __/   / /    / / / // / \\__ \\/ ,<    ",
" / /|  / /___  / /    / /_/ // / ___/ / /| |   ",
"/_/ |_/_____/ /_/    /_____/___//____/_/ |_|   "
    };

    int rows = sizeof(text_art) / sizeof(text_art[0]);
    for (int i = 0; i < rows; i++) {
        printf(RED "%s\n" RESET, text_art[i]);
    }
}

int main(int argc, char *argv[])
{
    display();
    // 判断登录信息格式
    if(strcmp(argv[1], "-u") != 0 || strcmp(argv[3], "-p") != 0){  
        printf("登录信息格式有误, 请重新登录.\n");
        return 0;
    }
    // 再判断用户名是否有特殊字符
    for(int i=0; i<strlen(argv[2]); i++){
        //printf("第%d个字符为: %c\n", i, argv[2][i]);
        if((argv[2][i] < '0' || argv[2][i] > '9') && 
            (argv[2][i] < 'A' || argv[2][i] > 'Z') && 
            (argv[2][i] < 'a' || argv[2][i] > 'z')){
                printf("用户名只能使用数字和字母, 不能使用特殊字符.\n");
                return 0;
            }
    }
    // 绑定ip和端口
    char ip[100] = {0};
    load_config("ip", ip);
    char port[100] = {0};
    load_config("port", port);
    
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(port));
    addr.sin_addr.s_addr = inet_addr(ip);

    connect(socket_fd, (struct sockaddr *)&addr, sizeof(addr));
    // 初始化请求报文
    request_t *req = (request_t *)malloc(sizeof(request_t));
    memset(req, 0, sizeof(request_t));
    strcpy(req->path, "/");
    response_t *res = (response_t *)malloc(sizeof(response_t));
    memset(res, 0, sizeof(response_t));
    // 是否已经登录
    int is_login = 0;

    if(login(req, res, argv, socket_fd) != 0){
        is_login = 0;
        printf("%s\n", res->args);
        printf("登录失败.\n");
        return 0;
    }
    printf("%s\n", res->args);
    is_login = 1;
    
    while (is_login == 1)
    {
        memset(req->args, 0, sizeof(req->args));
        printf("\033[1;46;37mclient@%s%s$ \033[0m", req->user_name, req->path);
        fflush(stdout);
        // 到这是正式开始输入命令, req.user_name一直是登陆时的不变了

        // 读标准输入
        char buf[1024] = {0};
        read(STDIN_FILENO, buf, sizeof(buf));
        //printf("buf : %s\n", buf);
        // 进行命令分析->拼接报文->发送报文
        int ret = analyze_cmd(socket_fd, buf, req);
        if (ret == -1)
        {
            printf("服务器响应错误\n");
            continue;
        }
        if (ret == 1)
        {
            printf("非法命令, 请重新输入.\n");
            continue;
        }
        if (ret == 2)
        {
            // 退出
            break;
        }
    }

    free(req);
    free(res);
    close(socket_fd);
    return 0;
}
